function update_profile(row) {
    try {
        var first_effective_index = $("#user-table").find("tr:first td").size() - 5;

        var email = $(row).find("td:first").text().trim();

        var nick = $(row).find("td").eq(first_effective_index).find("input").val();
        if (typeof nick == "undefined") {
            nick = "";
        } else {
            nick = nick.trim();
        }
        var desc = $(row).find("td").eq(first_effective_index+1).text().trim();
        var tags = $(row).find("td").eq(first_effective_index+2).text().trim();
        var photo = $(row).find("td").eq(first_effective_index+3).text().trim();

        if (tags.length > 0) {
            tags = tags.replace(/#/g, ',');
        }

        if (nick.length > 0 || desc.length > 0 || tags.length > 0 || photo.length > 0) {
            var cmd = sprintf('-e "%s" -c "%s" -d "%s" -i "%s" -t "%s"',
                              email, nick, desc, photo, tags);

            $(row).find('td:last').text('正在更新profile: ' + cmd);

            ++profile_updates_in_execution;
            $.ajax({
                url: 'index.php?ajax',
                type: 'post',
                data: {'cmd': cmd},
                success: function(data) {
                    $(row).find('td:last').text(data);
                    --profile_updates_in_execution;
                },
                error: function(data) {
                    $(row).find('td:last').text("error: " + data);
                    --profile_updates_in_execution;
                }
            });
            $(row).find('td:last').load(
                'index.php?ajax',
                {'cmd': cmd},
                function() {
                    --profile_updates_in_execution;
                }
            );
        }

    } catch(err) {
        alert('很不幸，update_profile 出错啦:' + err);
    }
}

function polite_update_profile(row) {
    if (profile_updates_in_execution < 5) {
        update_profile(row);
    } else {
        $(row).find('td:last').text('等待更新profile...');
        setTimeout(function() {
                       polite_update_profile(row);  
                   }, 5000);
    }
}

function insert_to_db(row) {
    try {
        $(row).children("td:last").text('写入数据库中...');

        var last_effective_index = $("#user-table").find("tr:first td").size() - 5;
        // Get the column names to DB, update string, insert string and finally the SQL statment
        var str_column = '';
        var str_update = '';
        var str_insert = '';
        var columns = $("#user-table").find("tr:first td").slice(0, last_effective_index);

        var items = $(row).find('td');

        $(columns).each(function(index, value) {
            str_column += $(value).text() + ',';
            str_insert += sprintf('"%s",', $($(items).get(index)).text());
            str_update += sprintf('%s = "%s",',
                                  $(value).text(),
                                  $($(items).get(index)).text());
        });

        str_column = str_column.slice(0, -1);
        str_insert = str_insert.slice(0, -1);
        str_update = str_update.slice(0, -1);

        var sql = sprintf('insert into sina_user(%s) values(%s) on duplicate key update %s',
                          str_column, str_insert, str_update);

        // Use ajax to send the SQL request
        $.ajax({
            url: 'mysql.php',
            type: "POST",
            data: {
                sql: sql
            },
            success: function(data) {
                $(row).find('td:last').text(data);
                if (data.indexOf('fail') != 0) {
                    polite_update_profile(row);
                }
            },
            error: function(data) {
                $(row.find('td:last')).text("error: " + data);
            }
        });
    } catch(err) {
        alert('很不幸，insert_to_db 出错了:' + err);
    }
}

function update_row(btn) {
    insert_to_db($(btn).parents('tr:first'));
}

var profile_updates_in_execution = 0;

$(document).ready(function() {
    $("#user-table").find('tr:gt(0)').each(function(index, data){
        $(data).find('td:last').dblclick(
            function(event) {
                $(event.target).html('<button onclick="update_row(this);">update</button>');
            });
    });

    $("#submit-ajax").click(function() {
        // Do the uploading here, using AJAX
        try {
            var table = $("#user-table");
            var status_col_index = $(table).find("tr:first td").size() - 1;
            var all_row = $(table).find('tr:gt(0)');
            $(all_row).each(function(index, row) {
                insert_to_db(row);
            });

        } catch (err) {
            alert('很不幸，出错了:' + err);
        }
    });

});